//
//  URLManager.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/10/12.
//  Copyright © 2019 BellaZhou. All rights reserved.
//
//  about networking
//  请求方式：GET/POST
//  请求头：
//  请求格式：
//
//

import UIKit
let imHostURL = "http://im.cqvip.com"
let imPath = "/api/"
let createToken = "Token/CreateToken" //参数: Password=appsecre&Username=qikanapp
let getAppBannerMsg = "RequestMsgInfoApi/GetAppbannerMsg" //参数: siteId=14

let apiHostURL = "http://api.cqvip.com"
let apiPath = "/qikanapp/"
let IPhoneVersionCheck = "IPhoneVersionCheck.ashx"
let GuessFavoriteMedia = "GuessFavoriteMedia.ashx"
let GetHotWords = "GetHotWords.ashx"
let GuessFavorite = "GuessFavorite.ashx"
let GetInfoNew = "GetInfoNew.ashx" //参数: key=662172888&type=article

let interfaceHostURL = "http://interface.cqvip.com"
let interfacePath = "/api/account/"
let getapiticket = "getapiticket"

enum TypeId {
    case artical
    case media
}

//MARK: demo for block receive data
class URLManager: NSObject {
    static let sharedURLManager: URLManager = {
        let instance = URLManager.init()
        return instance
    }()
    var success: successClosure?
    func startLoad(_ urlString: String) { // http://im.cqvip.com/
        let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                self.handleError(error: error)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse,
                (200...299).contains(httpResponse.statusCode) else {
                    self.handle(response: response as! HTTPURLResponse)
                return
            }
            if let mimeType = httpResponse.mimeType, mimeType == "text/html",
                let data = data {
                DispatchQueue.main.async {
                    self.success!(data, urlString)
                }
            }
        }
        task.resume()
    }
}

//MARK: demo for delegete receive data
class URLDelegateManager: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate, URLSessionDownloadDelegate {
    static let sharedURLDelegateManager: URLDelegateManager = {
        let instance = URLDelegateManager.init()
        return instance
    }()
    private lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        if #available(iOS 11.0, *) {
            configuration.waitsForConnectivity = true
        } else {
            // Fallback on earlier versions
        }
        configuration.requestCachePolicy = NSURLRequest.CachePolicy.useProtocolCachePolicy
        return URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    }()
    var receivedData: Data?
    func startLoad(_ urlSting: String) {
        let url = URL(string: urlSting)!
        receivedData = Data()
        let task = session.dataTask(with: url)
        task.resume()
    }
    // delegate methods
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,
                    completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
        guard let response = response as? HTTPURLResponse,
            (200...299).contains(response.statusCode),
            let mimeType = response.mimeType,
            mimeType == "text/html" else {
            completionHandler(.cancel)
            return
        }
        completionHandler(.allow)
    }
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        self.receivedData?.append(data)
        print("self.receiverdData: \(self.receivedData ?? Data())")
    }
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        DispatchQueue.main.async {
            if let error = error {
                self.handleError(error: error)
            } else if let receivedData = self.receivedData,
                let string = String(data: receivedData, encoding: .utf8) {
                
                print("通过delegate 最后的结果: \(string)")
               
            }
        }
    }
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        
    }
}
enum RequestMethod {
    case post
    case get
}
typealias successClosure = (_ responseString: Data?, _ urlString: String) -> ()
//MARK: Demo for upload task
class UploadingData: NSObject {
    static let sharedUploadingData: UploadingData = {
        let instance = UploadingData.init()
        return instance
    }()
    var success: successClosure?
    func uploadData(_ urlString: String, _ dataString: String, _ requestMethod: RequestMethod) {
        let uploadData = dataString.data(using: .utf8) //默认的Content-Type    application/x-www-form-urlencoded
        let url = URL(string: urlString)!
        var request = URLRequest(url: url)
        switch requestMethod {
        case .post:
            request.httpMethod = "Post"
        case .get:
            request.httpMethod = "Get"
        }
        let task = URLSession.shared.uploadTask(with: request, from: uploadData) { (data, response, error) in
            if let error = error {
                self.handleError(error: error)
                return
            }
            guard let httpResponse = response as? HTTPURLResponse,
                (200...299).contains(httpResponse.statusCode) else {
                    self.handle(response: response as! HTTPURLResponse)
                return
            }
            /*
             let mimeType = httpResponse.mimeType,
             mimeType == "application/json" || mimeType == "text/plain",
             */
            if let data = data {
                if self.success != nil {
                    DispatchQueue.main.sync {
                        self.success!(data, urlString)
                    }
                }
            }
        }
        task.resume()
    }
}
extension URLManager {
    func handleError(error: Error) -> Void {
        print("error: \(error)")
    }
    func handle(response: HTTPURLResponse) -> Void {
        print("response: \(response)")
    }
}
extension URLDelegateManager {
    func handleError(error: Error) -> Void {
        print("error: \(error)")
    }
    func handle(response: HTTPURLResponse) -> Void {
        print("response: \(response)")
    }
}
extension UploadingData {
    func handleError(error: Error) -> Void {
        print("error: \(error)")
    }
    func handle(response: HTTPURLResponse) -> Void {
        print("response: \(response)")
    }
}

struct BannerMsg: Codable {
    var id: Int?
    var title: String?
    var bannerImgUrl: URL?
    var bannerContentOutUrl: String?
    var linktype: Int?
}

struct GuessFavoriteResponseDict: Codable {
    var state: String?
    var msg: String?
    var datetime: String?
    var result: GuessFavoriteResultDict?
    var Count: Int?
    var message: String?
    var tokens: String?
}
struct GuessFavoriteResultDict: Codable {
    var type: String?
    var list: [GuessFavoriteListItem]?
}
struct GuessFavoriteListItem: Codable {
    var keyword_e: String?
    var zkcouplingcount: String?
    var volumn: String?
    var keyword_c: String?
    var zkrefercount: String?
    var issn: String?
    var range: String?
    var subjectnum: String?
    var endpage: String?
    var introduce: String?
    var beginpage: String?
    var type: String?
    var processdate: String?
    var title_e: String?
    var zkbycount: String?
    var vol: String?
    var title_c: String?
    var _id: String?
    var showwriter: String?
    var author_e: String?
    var pagecount: String?
    var organs: String?
    var zkbycount_sec: String?
    var media_e: String?
    var imburse: String?
    var media_c: String?
    var accessmode: String?
    var zkrefercount_sec: String?
    var medias_qk: String?
    var class_: String? //class
    var zkstrbyids: String?
    var specialnum: String?
    var classtypes: String?
    var num: String?
    var remark_e: String?
    var showorgan: String?
    var zkbycouplingcount: String?
    var remark_c: String?
    var writers: String?
    var years: String?
    var gch: String?
    var zkreferids_real: String?
}

struct GuessFavoriteMediaResponseDict: Codable {
    var state: String?
    var msg: String?
    var datetime: String?
    var result: GuessFavoriteMediaResultDict?
    var Count: Int?
    var message: String?
    var tokens: String?
}
struct GuessFavoriteMediaResultDict: Codable {
    var list: [GuessFavoriteMediaListItem]?
}
struct GuessFavoriteMediaListItem: Codable {
    var zkbyinfo: String?
    var medias_by: String?
    var zkfwcount: String?
    var aliasid: String?
    var zkfwinfo: String?
    var issn: String?
    var subjects: String?
    var score: Int?
    var organizers: String?
    var publisher: String?
    var lngrangeid: String?
    var zkbycount: String?
    var _id: String?
    var gch5: String?
    var mediatypeid: String?
    var organs: String?
    var zkhindex: String?
    var numcount: String?
    var periodtype: String?
    var FW_: Int? //#FW
    var supp_alias_text: String? // supp:alias_text
    var oldname: String?
    var classtypes: String?
    var funds: String?
    var lastnum: String?
    var cn: String?
    var writers: String?
    var gch: String?
    var impactfactor: String?
    var media: String?
    var mediapic: URL?
}
struct GetInfoDictArticalModel: Codable {
    var state: String
    var msg: String
    var datetime: String
    var result: GetInfoResultArticalModel
    var Count: Int
    var message: String
    var tokens: String
}
struct GetInfoResultArticalModel: Codable {
    var type: String
    var transfer: Bool
    var down: Bool
    var collect: Bool
    var obj: GuessFavoriteListItem?
}
struct GetInfoDictMediaModel: Codable {
    var state: String?
    var msg: String?
    var datetime: String?
    var result: GetInfoResultMediaModel?
    var Count: Int?
    var message: String?
    var tokens: String?
}
struct GetInfoResultMediaModel: Codable {
    var num: [MediaNumModel]?
    var obj: MediaObjModel?
    var type: String?
}
struct MediaNumModel: Codable {
    var num: String
    var gch5: String
    var year: String
}
struct MediaObjModel: Codable {
    var zkfwcount: String?
    var issn: String?
    var tel: String?
    var organizers: String?
    var publisher: String?
    var lngrangeid: String?
    var unitprice: String?
    var zkbycount: String?
    var _id: String?
    var gch5: String?
    var openformat: String?
    var zkhindex: String?
    var periodtype: String?
    var headeditor: String?
    var supp_alias_text: String? //supp:alias_text
    var oldname: String?
    var postcode: String?
    var editor: String?
    var price: String?
    var lastnum: String?
    var publishtime: String?
    var email: String?
    var cn: String?
    var address: String?
    var awards: String?
    var yfdh: String?
    var gch: String?
    var introduction: String?
    var mediapic: URL?
    var medias_by: String?
    var subjects: String?
    var organs: String?
    var classtypes: String?
    var funds: String?
    var writers: String?
    var listLngrangeid: String?
}
struct NumInfoDictModel: Codable {
    var state: String
    var msg: String
    var datetime: String
    var Count: Int
    var message: String
    var tokens: String
    var result: NumInfoResultModel
}
struct NumInfoResultModel: Codable {
    var type: String
    var list: [NumInfoItemModel]
}
struct NumInfoItemModel: Codable {
    var Lngid: String
    var Beginpage: String
    var Endpage: String
    var Title: String
    var Writer: String
}
struct SearchMediaDictModel: Codable {
    var state: String
    var msg: String
    var datetime: String
    var Count: Int
    var message: String
    var tokens: String
    var result: SearchMediaResultModel
}
struct SearchMediaResultModel: Codable {
    var type: String
    var list: [SearchMediaItemModel]
}
struct SearchMediaItemModel: Codable {
    var zkfwcount: String
    var zkbycount: String
    var _id: String
    var subjects: String
    var gch5: String
    //var FW_: Int? //#FW
    //var score: Int
    var gch: String
    var media: String
    var zkhindex: String
    var publisher: String
}
struct DomainResult: Codable {
    var result: [DomainItemObject]
}
struct DomainItemObject: Codable {
    var _id: String
    var name: String
//    var subjects: String
//    var zkfwcount: String
//    var zkbycount: String
//    var zkhindex: String
}
